<template>
  <template v-if="userStore.is_superuser">
    <div class="main">
      <div class="query">
        <el-card>
          <el-form
            :inline="true"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <el-form-item label="用户名:">
              <el-input
                placeholder="请你输入搜索用户名"
                v-model="keywords"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="default"
                :disabled="keywords ? false : true"
                :icon="Search"
                @click="search"
              >
                搜索
              </el-button>
              <el-button type="primary" size="default" @click="reset">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <!-- 用户列表 -->
      <div class="list">
        <el-card>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column
              prop="user_id"
              label="用户ID"
              width="80"
              align="center"
            />
            <el-table-column
              prop="username"
              label="用户名"
              width="180"
              align="center"
            />
            <el-table-column
              prop="nickname"
              label="昵称"
              width="180"
              align="center"
            />
            <el-table-column
              prop="email"
              label="邮箱"
              width="240"
              align="center"
            />
            <el-table-column
              prop="is_superuser"
              label="是否为管理员"
              width="180"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <!-- v-slot指令和$index变量来获取当前行的索引 -->
              <template #="{ row, $index }">
                <el-button
                  type="primary"
                  size="small"
                  icon="Edit"
                  @click="editUser(row.user_id)"
                >
                  编辑
                </el-button>
                <el-popconfirm
                  :title="`你确定要删除${row.username}?`"
                  width="260px"
                  @confirm="deleteUser(row.user_id)"
                >
                  <!-- #reference:模板中给元素或组件添加引用的特殊语法 -->
                  <template #reference>
                    <el-button type="danger" size="small" icon="Delete">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[5]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getUser"
        />
      </div>
      <!-- 修改用户信息对话框 -->
      <div class="dialog">
        <el-dialog
          :close-on-click-modal="false"
          v-model="dialogFormVisible"
          title="编辑用户信息"
        >
          <el-form :model="form" :rules="rules" ref="forms">
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" :label-width="formLabelWidth">
              <el-input v-model="form.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item
              label="邮箱"
              :label-width="formLabelWidth"
              prop="email"
            >
              <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmEdit">确认</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </template>
  <template v-else>
    <div class="main">该用户不是管理员，无权限查看用户列表</div>
  </template>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import type { FormInstance } from 'element-plus'
// 引入管理员获取用户相关操作的接口
import {
  reqUserList,
  reqInfo,
  reqDelete,
  reqUser,
  reqEdit,
} from '@/api/user/index'
// 定义响应式数据：收集用户输入进来的用户名或邮箱
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const keywords = ref<string>('')
// 表格数据
const tableData = ref([])
// 数据总数
let total = ref<number>(0)
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)
// 重置按钮
const reset = () => {
  keywords.value = ''
  getUser()
}
// 搜索按钮
const search = async () => {
  let res = await reqInfo(keywords.value)
  if (res.code === 200) {
    tableData.value = res.data.results
    total.value = res.data.total_count
  } else {
    ElNotification({
      message: res.result.error,
      type: 'error',
    })
  }
}
// 组件加载完毕
onMounted(() => {
  getUser()
})
// 获取用户列表
const getUser = async () => {
  let res = await reqUserList(pageNo.value)
  if (res) {
    tableData.value = res.data.results // 用户数据
    total.value = res.data.total_count // 数据总量
  } else {
    ElNotification({
      message: '该用户不是管理员，无权限',
      type: 'error',
    })
  }
}
// 删除用户信息(只有管理员才可以删除用户，普通用户不行)
const deleteUser = async (id: number) => {
  let res = await reqDelete(id)
  if (res.code === 200) {
    ElNotification({
      message: res.msg,
      type: 'success',
    })
    // 删除成功过后要更新用户列表
    getUser()
  }
}
// 对话框
const dialogFormVisible = ref<boolean>(false)
const formLabelWidth = '140px'
// 收集修改用户信息对话框的数据
const form = reactive({
  username: '',
  nickname: '',
  email: '',
})
const userId = ref<number>()
// 编辑用户信息
const editUser = async (id: any) => {
  dialogFormVisible.value = true // 显示对话框
  // 收集当前编辑用户的ID，方便执行确认编辑函数时使用
  userId.value = id
  let res = await reqUser(id)
  if (res.code === 200) {
    form.username = res.data.username
    form.nickname = res.data.nickname
    form.email = res.data.email
  }
}
// 获取el-form修改用户信息组件
let forms = ref()
// 确认修改用户信息
const confirmEdit = async () => {
  // 保证表单校验通过之后再发请求
  await forms.value.validate()
  dialogFormVisible.value = false // 关闭对话框
  console.log('数据为:', form, 'id为:', userId.value)
  let res = await reqEdit(userId.value, form)
  if (res.code === 200) {
    ElNotification({
      message: res.msg,
      type: 'success',
    })
    getUser()
  } else {
    ElNotification({
      message: res.error_msg,
      type: 'error',
    })
  }
}
// 自定义验证邮箱规则函数
const validatorEmail = (rule: any, value: any, callback: any) => {
  let regExp = /^[a-zA-Z0-9]{5,11}@(qq\.com|163\.com)$/
  if (regExp.test(value)) {
    callback()
  } else {
    callback(
      new Error('请输入符合要求的邮箱，例如：xxxx@qq.com 或 xxxx@163.com'),
    )
  }
}
const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length >= 5 && value.length <= 11) {
    callback()
  } else {
    callback(new Error('账号长度为5-11位之间'))
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  let regExp = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{4,11}$/
  if (regExp.test(value)) {
    callback()
  } else {
    callback(new Error('密码必须包含至少1个字母和1个数字，且长度为4-11位'))
  }
}
//定义表单校验需要配置对象
const rules = {
  email: [{ trigger: 'change', validator: validatorEmail }],
}
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  .query {
    height: 80px;
    width: 100%;
    .form {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .list {
    margin: 30px 0;
    .add {
      margin-bottom: 20px;
    }
  }
  .pagination {
    margin: 80px 0;
  }
  .dialog {
    .el-button--text {
      margin-right: 15px;
    }
    .el-input {
      width: 480px;
    }
    .dialog-footer button:first-child {
      margin-right: 10px;
    }
  }
}
</style>
